package authorizationAdmin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/authorizationAdmin/logic"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	pbAuthorizationAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/authorizationAdmin"
	"grpc.getaway.adminspro.padmins.com/pkg/support/log"
)

func (rpc *auth) Permission(ctx context.Context, pb *pbAuthorizationAdmin.PermissionReq) (*pbAuthorizationAdmin.PermissionResp, error) {
	logger := log.WithContext(ctx)
	logger.Info("Permission")
	row, e := logic.GetInfo(ctx, pb.Id)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	roles, e := logic.GetRoles(ctx, pb.Id)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	resourceIds, e := logic.GetResourceIdsByAdminId(ctx, pb.Id)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	permission, e := logic.Permission(ctx, resourceIds, pb.Resource)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	return &pbAuthorizationAdmin.PermissionResp{
		Admin: &pbAuthorizationAdmin.Admin{
			Id:              row["id"].(int64),
			Email:           row["email"].(string),
			Username:        row["username"].(string),
			Nickname:        row["nickname"].(string),
			Avatar:          row["avatar"].(string),
			Token:           row["token"].(string),
			TokenExpiryTime: row["token_expiry_time"].(string),
			Status:          int32(row["status"].(int64)),
			LoginTime:       row["login_time"].(string),
			CreateTime:      row["create_time"].(string),
			UpdateTime:      row["update_time"].(string),
		},
		Roles:       roles,
		ResourceIds: resourceIds,
		Permission:  permission,
	}, nil
}
